﻿using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using XCore.Authorization;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Controllers;
using XCore.Extensions;
using SaaS.Cache.Auths;

namespace Web.Client.Utils
{
    /// <summary>
    /// 授权过滤器
    /// </summary>
    public class AuthorizationFilter : ActionFilterAttribute
    {
        private readonly UserAuthCacheService _userCacheService;
        public AuthorizationFilter(UserAuthCacheService userCacheService)
        {
            _userCacheService = userCacheService;
        }
        /// <summary>
        /// 执行之后
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
        }
        /// <summary>
        /// 执行之前
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var authoriza = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo.GetCustomAttributes(typeof(PermissionAttribute), false).FirstOrDefault() as PermissionAttribute;
            if (authoriza != null)
            {
                int? userId = context.HttpContext.GetUserId();
                var authorization = context.HttpContext.Request.Headers.Where(c => c.Key == "Authorization").FirstOrDefault().Value;
                if (authorization.Count == 0 || !userId.HasValue) throw new AuthorizationException("用户未登录");
                if (!_userCacheService.CheckUserToken(userId.Value, authorization.ToString())) throw new AuthorizationException("用户登录已过期");
            }
            base.OnActionExecuting(context);
        }
    }
}
